import os.path

import requests

import re
from moviepy.editor import VideoFileClip, AudioFileClip
import json


def download_video_from_bilibili(video_url='', base_path="video", cookies=''):
    url = 'https://www.bilibili.com/video/BV1jt421c7yN/'

    headers = {
        # Referer 防盗链 告诉服务器你请求链接是从哪里跳转过来的
        # "Referer": "https://www.bilibili.com/video/BV1454y187Er/",
        "Referer": url,
        # User-Agent 用户代理, 表示浏览器/设备基本身份信息
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
        "Cookie": cookies
    }
    # 发送请求
    response = requests.get(url=url, headers=headers)
    html = response.text
    print(html)
    # 解析数据: 提取视频标题
    title = re.findall('title="(.*?)"', html)[0]
    print(title)
    # 提取视频信息
    info = re.findall('window.__playinfo__=(.*?)</script>', html)[0]
    # info -> json字符串转成json字典
    json_data = json.loads(info)
    # 提取视频链接
    video_url = json_data['data']['dash']['video'][0]['baseUrl']
    print(video_url)
    # 提取音频链接
    audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
    print(audio_url)
    video_content = requests.get(url=video_url, headers=headers).content
    # 获取音频内容
    audio_content = requests.get(url=audio_url, headers=headers).content
    # 保存数据
    os.makedirs(base_path, exist_ok=True)
    with open('{}\\'.format(base_path) + title + '.mp4', mode='wb') as v:
        v.write(video_content)
    with open('{}\\'.format(base_path) + title + '.mp3', mode='wb') as a:
        a.write(audio_content)
    # 视频和音频文件的路径
    video_path = '{}\\'.format(base_path) + title + '.mp4'
    audio_path = '{}\\'.format(base_path) + title + '.mp3'

    # 加载视频和音频文件
    video_clip = VideoFileClip(video_path)
    audio_clip = AudioFileClip(audio_path)

    # 确保音频和视频长度相同
    audio_clip = audio_clip.set_duration(video_clip.duration)

    # 将音频添加到视频中
    final_clip = video_clip.set_audio(audio_clip)

    # 导出最终视频
    final_clip.write_videofile('video\\' + title + '_final.mp4', codec='libx264', audio_codec='aac')
    return


if __name__ == '__main__':
    download_video_from_bilibili()
